import 'package:app_info/app_info.dart';
import 'package:app_info/info/appsflyer.dart';
import 'package:get/get.dart';
import 'package:smartloan_mdc/route/app_routes.dart';
import 'package:smartloan_mdc/utils/auth/auth.dart';
import 'package:smartloan_mdc/utils/common/utils.dart';
import 'package:trace/trace.dart';

import '../javascript_channel.dart';

// getLoginInfo
class GetLoginInfo extends JavaScriptChannel {
  @override
  List<String> get actions => ['getLoginInfo'];

  @override
  onReceive(Map newMsg) {
    if (Auth.isLogin()) {
      callBack(true, {'token': Auth.getLoginKey()});
    } else {
      Get.toNamed(AppRoutes.phone);
    }
  }
}

// toLogin logout
class ToAuth extends JavaScriptChannel {
  @override
  List<String> get actions => ['toLogin', 'logout'];

  @override
  onReceive(Map newMsg) async {
    if (Auth.isLogin()) {
      Auth.logout();
    }
    await webCtrl?.clearCache();
    Get.offAndToNamed(AppRoutes.phone);
  }
}

// getVersionName
class GetVersionName extends JavaScriptChannel {
  @override
  List<String> get actions => ['getVersionName'];

  @override
  onReceive(Map newMsg) {
    callBack(true, {'versionName': AppInfo().version});
  }
}

// getPackageName
class GetPackageName extends JavaScriptChannel {
  @override
  List<String> get actions => ['getPackageName'];

  @override
  onReceive(Map newMsg) {
    callBack(true, {
      'packageName': AppInfo().packageName,
      'androidId': AppInfo().androidId,
      'imei': '0000000000000000',
      'afid': AppsFlyer().afId,
      'appVersion': AppInfo().version,
      'appName': AppInfo().appName,
      'traceId': Trace().traceId
    });
  }
}

// setNewToken
class SetNewToken extends JavaScriptChannel {
  @override
  List<String> get actions => ['setNewToken'];

  @override
  onReceive(Map newMsg) {
    Auth.setToken(message?['token']);
  }
}

// ToWhatsapp
class ToWhatsapp extends JavaScriptChannel {
  @override
  List<String> get actions => ['toWhatsapp'];

  @override
  onReceive(Map newMsg) {
    final Uri toWhatLaunch = Uri.https('api.whatsapp.com', '/send', {'phone': newMsg?['phone']});
    Utils.appLaunch(toWhatLaunch.toString());
  }
}

// toGooglePlayer
class ToGooglePlayer extends JavaScriptChannel {
  @override
  List<String> get actions => ['toGooglePlayer'];

  @override
  onReceive(Map newMsg) {
    String idOrUrl = newMsg['packageId'];
    Utils.toGooglePlay(idOrUrl);
  }
}

// logEventByAF
class LogEventByAF extends JavaScriptChannel {
  @override
  List<String> get actions => ['logEventByAF'];

  @override
  onReceive(Map newMsg) {
    AppsFlyer().logEvent(newMsg?['data']['event']);
  }
}

